#pragma once
#include <pthread.h>
#include <iostream>
#include <queue>
#include "common.hpp"

template <class T>
class BlockQueue
{
public:
    BlockQueue(int capacity) :_capacity(capacity)
    {
        pthread_mutex_init(&_mtx, nullptr);
        pthread_cond_init(&_c_cond, nullptr);
        pthread_cond_init(&_p_cond, nullptr);
    }

    void push(const T& in)
    {
        LockGuard lock(&_mtx);
        while(_q.size() == _capacity){
            pthread_cond_wait(&_p_cond, &_mtx);
        }
        _q.push(in);
        pthread_cond_broadcast(&_c_cond);
    }

    void pop(T* out)
    {
        LockGuard lock(&_mtx);
        while(_q.empty()){
            pthread_cond_wait(&_c_cond, &_mtx);
        }
        *out = _q.front();
        _q.pop();
        pthread_cond_broadcast(&_p_cond);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mtx);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }
private:
    std::queue<T> _q;
    int _capacity;
    pthread_mutex_t _mtx;
    pthread_cond_t _c_cond;
    pthread_cond_t _p_cond;
};